import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { Http } from '@capacitor-community/http';
import { Capacitor } from '@capacitor/core';
import { Directory, Filesystem } from '@capacitor/filesystem';
import { LoadingController, Platform } from '@ionic/angular';
import { Select, Store } from '@ngxs/store';
import { Observable, Subscription } from 'rxjs';
import { Sentence } from 'src/app/model/sentence';
import { retry } from 'ts-retry-promise';
import { GetSentences, UpdateSequenceNo } from '../store/actions/app.action';
import { AppState } from '../store/state/app.state';
import { PlayerComponent } from './components/player/player.component';
import { ReadingService } from './services/reading.service';

@Component({
  selector: 'app-reading',
  templateUrl: 'reading.page.html',
  styleUrls: ['reading.page.scss'],
})
export class ReadingPage implements OnInit, OnDestroy {
  @ViewChild(PlayerComponent)
  public player: PlayerComponent;

  @Select(AppState.getCurrentSentence)
  public currentSentence: Observable<Sentence>;

  @Select(AppState.getSentences)
  public sentences: Observable<Sentence[]>;

  @Select(AppState.getCurrentChapterNo)
  public currentChapterNo: Observable<number>;

  @Select(AppState.getCurrentSequenceNo)
  public currentSequenceNo: Observable<number>;

  @Select(AppState.getAutoPlaying)
  public autoPlaying: Observable<boolean>;

  @Select(AppState.getWaitTime)
  public waitTime: Observable<number>;

  public englishChecked = true;
  public chineseChecked = true;

  private activateSubscription: Subscription;
  private inactivateSubscription: Subscription;
  private sentencesCount: number;

  constructor(public readingService: ReadingService,  private store: Store) {}

  public ngOnInit() {
    this.sentences.subscribe((ss) => {
      this.sentencesCount = ss.length;
    });
  }

  public ionViewDidLeave() {
    if (this.player.playing) {
      this.player.pause();
    }
  }
  public ngOnDestroy(): void {
    this.inactivateSubscription?.unsubscribe();
    this.activateSubscription?.unsubscribe();
  }

  public enChange(event: any) {
    this.englishChecked = event.detail.checked;
  }
  public zhChange(event: any) {
    this.chineseChecked = event.detail.checked;
  }

  public gotoPreviousChapter() {
    this.store.dispatch(new GetSentences(-1));
  }
  public gotoNextChapter() {
    this.store.dispatch(new GetSentences(1));
  }

  public loadNextSentence(currentsSequenceNo: number) {
    let nextSequenceNo = currentsSequenceNo + 1;
    if (nextSequenceNo > this.sentencesCount) {
      nextSequenceNo = 1;
    }
    this.store.dispatch(new UpdateSequenceNo(nextSequenceNo));
  }

  public slideNext(nextSequenceNo: number) {
    this.store.dispatch(new UpdateSequenceNo(nextSequenceNo));
  }

  public slidePrevious(previousSequenceNo: number) {
    this.store.dispatch(new UpdateSequenceNo(previousSequenceNo));
  }


}
